<template>
  <div class="attendance">
    <div class="attendance-search">
      <el-select v-model="pointsId" placeholder="请选择" size="small" class="mr10" v-if="type!=='pointDetail'">
        <el-option
          v-for="item in postList"
          :key="item.id"
          :label="item.name"
          :value="item.id">
        </el-option>
      </el-select>
      <el-date-picker
        v-model="monthDay"
        size="small"
        class="mr10"
        type="daterange"
        range-separator="至"
        :picker-options="pickerOptions2"
        format="yyyy-MM-dd"
        value-format="yyyy-MM-dd"
        start-placeholder="开始日期"
        end-placeholder="结束日期">
      </el-date-picker>
      <el-button
        type="primary"
        icon="el-icon-search"
        size="small"
        @click="handleQuery"
      >搜索
      </el-button>
      <el-button icon="el-icon-refresh" size="small" @click="resetQuery"
      >重置
      </el-button
      >
    </div>
    <div class="attendance-body mt10 logTable">
      <el-table
        size="small"
        :data="tableData"
        border
        style="width: 100%">
        <el-table-column
          prop="userID_Convert"
          label="姓名"
          align="center"
          fixed="left"
          width="120">
          <template slot-scope="scope">
            <span class="name-line" @click="checkLog(scope.row)">
              {{ scope.row.nickName }}
            </span>
          </template>
        </el-table-column>
<!--        <el-table-column-->
<!--          prop="postType_Convert"-->
<!--          align="center"-->
<!--          width="85"-->
<!--          fixed="left"-->
<!--          label="班次">-->
<!--          <template slot-scope="scope">-->
<!--            无-->
<!--          </template>-->
<!--        </el-table-column>-->
        <el-table-column
          prop="postTypeCount"
          align="center"
          width="85"
          fixed="left"
          label="核算公时">
          <template slot-scope="scope">
            0
          </template>
        </el-table-column>
        <el-table-column
          prop="accountHours"
          align="center"
          width="85"
          fixed="left"
          label="加班时长">
          <template slot-scope="scope">
            0
          </template>
        </el-table-column>
        <el-table-column
          prop="dayNameLine"
          align="center"
          width="85"
          :label="item.dayNameLine"
          :render-header="renderheader"
          class="log-td-box"
          v-for="(item, index) of dayMonth"
          :key="index">
          <template slot-scope="scope">
            <div style="background: #f6f6f6;padding: 6px 0;">
              {{scope.row.log[item.dayPoint]?(scope.row.log[item.dayPoint].signs?1:0):0}}
            </div>
          </template>
        </el-table-column>
      </el-table>
    </div>
    <sign_log_user :visible.sync="signVisible" :paramData="paramData" :monthDay="monthDay"></sign_log_user>
  </div>
</template>

<script>
import sign_log_user from "./sign_log_user";
import {
  listStagnationPoint
} from "@/api/system/stagnation_point";
import {
  schedulingUserAll
} from "@/api/system/attendLog";

export default {
  name: "log",
  props: ['type'],
  components: {sign_log_user},
  data() {
    return {
      activeName: 'userInfo',
      postList: [],
      pointsId: 0,
      monthDay: '',
      tableData: [],
      dayMonth: [],
      signVisible: false,
      paramData: null,
      week: ['日', '一', '二', '三', '四', '五', '六'],
      pickerOptions2: {
        onPick: function ({minDate, maxDate}) {
          if (minDate && !maxDate) {
            const currentDateTimestamp = minDate.getTime();
            const minDateTimestamp = currentDateTimestamp - 3600 * 1000 * 24 * 31;
            const maxDateTimestamp = currentDateTimestamp + 3600 * 1000 * 24 * 31;
            this.disabledDate = date => {
              const dateTimestamp = date.getTime();
              return dateTimestamp <= minDateTimestamp || dateTimestamp >= maxDateTimestamp;
            };
          }
        }
      }
    };
  },
  created() {
    // const date = new Date();
    // const year = date.getFullYear();
    // const month = date.getMonth() + 1;
    // const lastDay = new Date(year, month, 0).getDate();
    // this.monthDay = [`${this.newDate()}-01`, `${this.newDate()}-${lastDay}`] // 默认日期当月月初-月末
    this.resetQuery()
    this.getList() // 查询全部驻点
  },
  methods: {
    /** 查询单个用户考勤记录 */
    checkLog(item) {
      this.paramData = item.userId
      this.signVisible = true
    },
    /** 查询考勤记录 */
    getLogList() {
      let that = this
      this.$modal.loading("正在查询中，请稍候...");
      schedulingUserAll({startDay: this.monthDay[0], endDay: this.monthDay[1], pointsId: this.pointsId}).then(res => {
        console.log('res=>', res)
        for(let item of res.data){
          let day_ = {}
          for(let day of item.schedulingList){
            day_[day.day] = day
          }
          item.log = day_
        }
        this.tableData = this.$deepCopy(res.data)
        setTimeout(() => {
          that.$modal.closeLoading();
        }, 500)
      }).catch(res => {
        setTimeout(() => {
          that.$modal.closeLoading();
        }, 500)
      })
    },
    /** 查询岗位列表 */
    getList() {
      listStagnationPoint(this.queryParams).then(response => {
        response.rows.unshift({
          name: '全部',
          id: 0
        })
        this.postList = response.rows;
      });
    },
    renderheader(h, {column, $index}) {
      return h("div", {}, [
        h("div", {}, column.label.split(",")[0]),
        h("div", {}, column.label.split(",")[1]),
      ]);
    },
    newDate() {
      let date = new Date()
      let y = date.getFullYear()
      let m = date.getMonth() + 1
      m = m < 10 ? '0' + m : m
      return y + '-' + m
    },
    handleClick(tab, event) {
      console.log(tab, event);
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.dayTimeFn()
      this.getLogList() // 考勤记录列表
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.pointsId = 0
      const date = new Date();
      const year = date.getFullYear();
      const month = date.getMonth() + 1;
      const lastDay = new Date(year, month, 0).getDate();
      this.monthDay = [`${this.newDate()}-01`, `${this.newDate()}-${lastDay}`] // 默认日期当月月初-月末
      this.handleQuery();
    },
    dayTimeFn() {
      // 进入页面默认查询当月天数日期
      const dates = this.printDatesInRange(this.monthDay[0], this.monthDay[1]);
      this.dayMonth = dates.map(date => {
        let data_ = date.toISOString().split('T')[0]
        let time_ = data_.split('-')
        let firstDayOfMonth = new Date(data_)
        //该月第一天是周几?0表示周日，1表示周一...6表示周六
        let dayWeek = firstDayOfMonth.getDay()
        return {
          day: `${time_[1]}/${time_[2]}`,
          dayNameLine: `周${this.week[dayWeek]},${time_[1]}/${time_[2]}`,
          week: this.week[dayWeek],
          dayName: data_,
          dayPoint: data_.split('-').join('')
        }
      })
      console.log('this.dayMonth:', this.dayMonth)
    },
    printDatesInRange(date1, date2) {
      const startDate = new Date(date1);
      const endDate = new Date(date2);
      const dateArray = [];

      let currentDate = new Date(startDate);
      while (currentDate <= endDate) {
        dateArray.push(new Date(currentDate));
        currentDate.setDate(currentDate.getDate() + 1);
      }

      return dateArray;
    },
  }
}
</script>

<style scoped>

.name-line {
  cursor: pointer;
}

.name-line:hover {
  text-decoration: underline;
  color: #2a99ff;
}
</style>
